package repository

import (
	"errors"

	"away.wei/minidevpos/db"
	"away.wei/minidevpos/global"
	"away.wei/minidevpos/model"
	"gorm.io/gorm"
)

type ConfigrationRep struct{}

func (s *ConfigrationRep) Create(dto db.Configration) error {
	if (!errors.Is(global.DB.First(&db.Configration{}, "name = ?", dto.Name).Error, gorm.ErrRecordNotFound)) {
		return errors.New("存在相同的Name，不允许创建")
	}
	return global.DB.Create(&dto).Error
}

func (s *ConfigrationRep) Delete(ids []int) error {
	return global.DB.Delete(&db.Configration{}, "id in ?", ids).Error
}

func (s *ConfigrationRep) Update(dto db.Configration) error {
	return global.DB.Updates(&dto).Error
}

func (s *ConfigrationRep) GetByName(name string) (dto db.Configration, err error) {
	err = global.DB.First(&dto, "name=?", name).Error
	return dto, err
}

func (s *ConfigrationRep) GetPage(dto model.ConfigrationSearch) (list interface{}, total int64, err error) {
	limit := dto.PageSize
	offset := dto.PageSize * (dto.Page - 1)

	dbquery := global.DB.Model(&db.Configration{})
	var dtos []db.Configration

	if dto.Name != "" {
		dbquery = dbquery.Where("name like ?", "%"+dto.Name+"%")
	}

	err = dbquery.Count(&total).Error
	if err != nil {
		return
	}
	err = dbquery.Limit(limit).Offset(offset).Find(&dtos).Error
	return dtos, total, err
}
